package com.demo.rabbitmq.producer;

import com.demo.rabbitmq.config.PluginDirectExchangeEnum;
import com.demo.rabbitmq.config.PluginDirectRoutingKeyEnum;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 发送延时消息
 * RabbitMQ需要安装插件rabbitmq_delayed_message_exchange
 */
@Service
public class PluginDirectDelayProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void send(int i) {
        String exchange = PluginDirectExchangeEnum.PLUGIN_DIRECT_DELAY_EXCHANGE.getExchangeName();
        String routingKey = PluginDirectRoutingKeyEnum.PLUGIN_DIRECT_DELAY_QUEUE_ROUTING_KEY.getRoutingKeyName();
        String content = String.format("消息=%d，延时消息, 延时时间：%d秒, hello world! 当前时间：%s", i, i, new Date());
        rabbitTemplate.convertAndSend(exchange, routingKey, content, message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            // 毫秒为单位，指定此消息的延时时长
            message.getMessageProperties().setDelay(i * 1000);
            return message;
        });
    }
}
